package com.itheima.reggie.controller;

import com.itheima.reggie.common.R;
import com.itheima.reggie.entity.User;
import com.itheima.reggie.service.UserService;
import com.itheima.reggie.util.ValidateCodeUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpSession;
import java.util.Map;
import java.util.concurrent.TimeUnit;

/**
 * @author 黑马程序员
 */
@RestController
@RequestMapping("/user")
public class UserController {


    @Autowired
    private UserService userService;

    @Autowired
    private RedisTemplate redisTemplate;

    //处理发送短信的请求
    @PostMapping("/sendMsg")
    public R<String> sendMsg(@RequestBody User user, HttpSession session) {
        //1.接收手机号封装User对象
        //2.生成4位手机验证码
        String code = ValidateCodeUtils.generateValidateCode(4).toString();
        System.out.println("验证码：" + code);
        //3.发送手机验证码
        //SMSUtils.sendMessage("黑马旅游网","SMS_198917972",user.getPhone(),code);
        //4.将生成的验证码存储到session中（手机号作为key，验证码作为value）
        //session.setAttribute(user.getPhone(), code);

        //将验证码存入到缓存中,并设置过期时间5分钟
        redisTemplate.opsForValue().set(user.getPhone(),code,300,TimeUnit.SECONDS);


        //5.返回数据，输出成功
        return R.success("发送验证码短信成功");
    }


    /**
     * 处理用户端登录的请求
     * @param map
     * @param session
     * @return
     */
    @RequestMapping("/login")
    public R<User> login(@RequestBody Map<String, String> map, HttpSession session) {
        //1.接收数据封装到Map<String,String> map
        String phone = map.get("phone"); //输入手机号
        String userCode = map.get("code");  //用户输入的验证码

        //2.从session中获取存储的验证码
        //String sessionCode = (String) session.getAttribute(phone);

        //从缓存里面拿验证码
        String sessionCode = (String) redisTemplate.opsForValue().get(phone);

        //3.调用业务层进行登录操作,返回登录的用户对象
        User login = userService.login(phone, userCode, sessionCode);
        if (login != null) {
            //4.登录用户有效,写入用户的idsession(key="user")
            session.setAttribute("user", login.getId());
            //登录成功后,session的验证码就可以删除了
            //session.removeAttribute(phone);

            //将缓存中的验证码删除
            redisTemplate.delete(phone);

            //返回成功的数据
            return R.success(login);
        }

        //5.返回数据(登录的用户)
        return R.error("登录失败");
    }
}
